package org.example.esdemo.controller;

import org.example.esdemo.entity.Product;
import org.example.esdemo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/products")
public class ProductController {
    @Autowired
    private ProductService productService;

    // 创建产品
    @PostMapping
    public Product createProduct(@RequestBody Product product) {
        return productService.saveProduct(product);
    }

    // 批量创建产品
    @PostMapping("/batch")
    public Iterable<Product> createProducts(@RequestBody Iterable<Product> products) {
        return productService.saveAllProducts(products);
    }

    // 获取所有产品
    @GetMapping
    public Iterable<Product> getAllProducts() {
        return productService.getAllProducts();
    }

    // 根据ID获取产品
    @GetMapping("/{id}")
    public Optional<Product> getProductById(@PathVariable String id) {
        return productService.getProductById(id);
    }

    // 多条件搜索
    @GetMapping("/search")
    public List<Product> searchByNameAndCategory(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String category) {

        if (name != null && category != null) {
            return productService.getProductsByNameAndCategory(name, category);
        } else if (name != null) {
            return productService.getProductsByName(name);
        } else if (category != null) {
            return productService.getProductsByCategory(category);
        }
        return null;
    }

    // 价格区间搜索(分页)
    @GetMapping("/search/price")
    public Page<Product> searchByPriceBetween(
            @RequestParam BigDecimal minPrice,
            @RequestParam BigDecimal maxPrice,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        Pageable pageable = PageRequest.of(page, size);
        return productService.getProductsByPriceBetween(minPrice, maxPrice, pageable);
    }

    // 删除产品
    @DeleteMapping("/{id}")
    public void deleteProduct(@PathVariable String id) {
        productService.deleteProduct(id);
    }
}
